<?php
namespace app\index\controller;

use think\Request;
use think\Loader;
use think\Exception;
use think\Db;
use app\interfaces\model\Area as AreaModel;
use app\index\model\MemberAddress as MemberAddressModel;

class MemberAddress
{

    /**
     * 会员地址列表
     * @return array
     * @throws Exception
     */
    public function index()
    {
        // 获取参数
        $user_id = Request::instance()->param('member_id');

        if (empty($user_id)) throw new Exception('not Empty');
        // 展示数据
        $model = new MemberAddressModel();

        $result = $model->where(['member_id' => $user_id])->field('create_time,member_id', true)->order(['id' => 'desc'])->paginate(10);

        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }

    /**
     * 地址区域列表
     * @return array
     */
    public function area_list(){

        $area_deep = Request::instance()->param('area_deep',1);
        $area_parent_id =  Request::instance()->param('area_parent_id');
        $condition= [];
        if($area_parent_id) $condition['area_parent_id'] =  ['eq',$area_parent_id];
        if($area_deep) $condition['area_deep'] =  ['eq',$area_deep];
        $one_level = db('area')->where($condition)->select();


        return ['code' => 200, 'message' => '成功', 'data' => $one_level];
    }


    /*
     * 用户端 - 添加收货地址
     * @param  string $user_id      会员ID
     * @param  string $name         姓名
     * @param  string $phone        电话号
     * @param  string $area_id      地区ID
     * @param  string $area_info    地区描述
     * @param  string $address      详细地址
     * @param  string $status       地址默认
     */
    public function create()
    {
        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];
        // 获取参数
        $data = Request::instance()->param();
        $member_address = Db::name('MemberAddress')->where('member_id',$data['member_id'])->find();
        if(empty($member_address) && $data['status'] == 2) return ['code' => 402, 'message' => '您还没有默认的地址,请选择为默认地址'];
        // 提交数据
        $model = new MemberAddressModel();
        $result = $model->allowField(true)->save($data);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*
     * 用户端 - 更新收货地址
     * @param  string $id           ID
     * @param  string $name         姓名
     * @param  string $phone        电话号
     * @param  string $area_id      地区ID
     * @param  string $area_info    地区描述
     * @param  string $address      详细地址
     * @param  string $status       地址默认
     */
    public function update()
    {
        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['id']) || empty($data['name']) || empty($data['phone']) || empty($data['area_info']) || empty($data['address']) || empty($data['status'])) throw new Exception('not Empty');

        // 验证
        $validate = Loader::validate('MemberAddress','validate','','index');
        if (!$validate->scene('update')->check($data)) return ['code' => 402, 'message' => $validate->getError()];

        // 提交数据
        $model = new MemberAddressModel();
        // 判断是否有默认地址
        if ($data['status'] == 2) {//当前地址改成普通地址，而其他地址还没有设置默认地址;
            $find = $model->where(['member_id' => $data['member_id'], 'status' => 1 ,'id' => ['neq', $data['id']]])->find();//当前会员非当前id 等于1是有默认地址
            if (empty($find)) return ['code' => 401, 'message' => '我的地址里没有默认地址,请设置一个默认地址'];//给默认地址删除了，在修改的时候就必须得选择一个默认地址状态1
        }

        $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }
        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*
     * 用户端 - 删除收货地址
     * @param  string $id  ID
     */
    public function destroy($id)
    {
        if (empty($id)) throw new Exception('not Empty');
        $result = MemberAddressModel::destroy($id);
        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }
        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 用户端 - 默认收货地址
     * @param  string $id ID
     */
    public function set_default($id)
    {

        if (empty($id)) throw new Exception('not Empty');

        // 启动事务
        Db::startTrans();
        try {

            // 提交数据
            Db::name('member_address')->where(['id' => $id])->update(['status' => '1']);

            Db::name('member_address')->where(['id' => ['neq', $id]])->update(['status' => '2']);

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }

    }

}
